package com.evaluation.util;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import cn.hutool.core.lang.Filter;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.persistence.Column;

public class ColumnFieldUtil {

	public static <T> Field[] getColumField( T clazz ) {
		if( clazz == null ) {
			return new Field[0];
		}
		
		//AnnotationUtils.getAnnotation(annotation, annotationType)
		Field[] fields = ReflectUtil.getFields(clazz.getClass(), new Filter<Field>() {

			@Override
			public boolean accept(Field t) {
				
				Column column = t.getDeclaredAnnotation( Column.class );
				if( column == null || StrUtil.isBlank( column.name() ) ) {
					return false;
				}
				
				return true;
			}
			
		});
		
		return fields;
	}
	
	public static Object getValue( ResultSet rs, Field field ) throws SQLException {
		Column column = field.getDeclaredAnnotation( Column.class );
		var typeName = field.getGenericType().getTypeName();
		var columnName = column.name();
		
		if( String.class.getName().equals( typeName ) ) {
			return rs.getString( columnName );
		}
		else if( Integer.class.getName().equals( typeName ) || "int".equals( typeName ) ) {
			return rs.getInt( columnName );
		}
		else if( Long.class.getName().equals( typeName ) || "long".equals( typeName ) ) {
			return rs.getLong( columnName );
		}
		else if( Double.class.getName().equals( typeName ) || "double".equals( typeName ) ) {
			return rs.getDouble( columnName );
		}
		else if( Float.class.getName().equals( typeName ) || "float".equals( typeName ) ) {
			return rs.getFloat( columnName );
		}
		else if( BigDecimal.class.getName().equals( typeName ) ) {
			return rs.getBigDecimal( columnName );
		}
		else if( Boolean.class.getName().equals( typeName ) || "boolean".equals( typeName ) ) {
			return rs.getBoolean( columnName );
		}
		else if( Date.class.getName().equals( typeName ) ) {
			return rs.getTimestamp( columnName );
		}
		else {
			return rs.getObject( column.name() );
		}
		
	}
}
